// 通知服务 - 连接后端API
import axios from 'axios'
import config from '../config'

const API_BASE_URL = config.API_BASE_URL

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: config.API_TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('Notification API Error:', error)
    
    // 网络错误处理
    if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_REFUSED') {
      const fallbackError = new Error('BACKEND_UNAVAILABLE')
      fallbackError.isFallback = true
      return Promise.reject(fallbackError)
    }
    
    // 认证错误处理
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user_info')
    }
    
    return Promise.reject(error)
  }
)

// 模拟通知数据
const mockNotifications = [
  {
    id: 1,
    title: '系统维护通知',
    content: '系统将于今晚22:00-24:00进行维护，期间可能影响正常使用。',
    type: 'system',
    priority: 'high',
    status: 'unread',
    senderId: 1,
    senderName: '系统管理员',
    recipients: [1, 2, 3],
    channels: ['in_app', 'email'],
    createdAt: new Date().toISOString(),
    readAt: null
  },
  {
    id: 2,
    title: '工单状态更新',
    content: '您的工单 #12345 状态已更新为"处理中"。',
    type: 'ticket',
    priority: 'medium',
    status: 'read',
    senderId: 2,
    senderName: '客服小王',
    recipients: [3],
    channels: ['in_app'],
    createdAt: new Date(Date.now() - 3600000).toISOString(),
    readAt: new Date(Date.now() - 1800000).toISOString()
  },
  {
    id: 3,
    title: '安全提醒',
    content: '检测到异常登录行为，请及时检查账户安全。',
    type: 'security',
    priority: 'urgent',
    status: 'unread',
    senderId: 1,
    senderName: '系统管理员',
    recipients: [3],
    channels: ['in_app', 'email', 'sms'],
    createdAt: new Date(Date.now() - 7200000).toISOString(),
    readAt: null
  }
]

export const NotificationService = {
  // 获取通知列表
  async listNotifications(params = {}) {
    try {
      const response = await apiClient.get('/notifications', { params })
      
      if (response.code === 0) {
        console.log('✅ 使用真实API获取通知列表成功')
        return response.data
      } else {
        throw new Error(response.message || '获取通知列表失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟通知数据')
        return this.mockGetNotifications(params)
      }
      console.error('❌ 后端API获取通知列表失败，使用模拟数据:', error)
      return this.mockGetNotifications(params)
    }
  },

  // 获取通知详情
  async getNotification(id) {
    try {
      const response = await apiClient.get(`/notifications/${id}`)
      
      if (response.code === 0) {
        console.log('✅ 使用真实API获取通知详情成功')
        return response.data
      } else {
        throw new Error(response.message || '获取通知详情失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟通知详情')
        return this.mockGetNotification(id)
      }
      console.error('❌ 后端API获取通知详情失败，使用模拟数据:', error)
      return this.mockGetNotification(id)
    }
  },

  // 发送通知
  async sendNotification(notificationData) {
    try {
      const response = await apiClient.post('/notifications', notificationData)
      
      if (response.code === 0) {
        console.log('✅ 使用真实API发送通知成功')
        return response.data
      } else {
        throw new Error(response.message || '发送通知失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟发送通知')
        return this.mockSendNotification(notificationData)
      }
      console.error('❌ 后端API发送通知失败，使用模拟数据:', error)
      return this.mockSendNotification(notificationData)
    }
  },

  // 标记通知为已读
  async markAsRead(id) {
    try {
      const response = await apiClient.put(`/notifications/${id}/read`)
      
      if (response.code === 0) {
        console.log('✅ 使用真实API标记通知已读成功')
        return response.data
      } else {
        throw new Error(response.message || '标记已读失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟标记已读')
        return this.mockMarkAsRead(id)
      }
      console.error('❌ 后端API标记已读失败，使用模拟数据:', error)
      return this.mockMarkAsRead(id)
    }
  },

  // 标记通知为未读
  async markAsUnread(id) {
    try {
      const response = await apiClient.put(`/notifications/${id}/unread`)
      
      if (response.code === 0) {
        console.log('✅ 使用真实API标记通知未读成功')
        return response.data
      } else {
        throw new Error(response.message || '标记未读失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟标记未读')
        return this.mockMarkAsUnread(id)
      }
      console.error('❌ 后端API标记未读失败，使用模拟数据:', error)
      return this.mockMarkAsUnread(id)
    }
  },

  // 删除通知
  async deleteNotification(id) {
    try {
      const response = await apiClient.delete(`/notifications/${id}`)
      
      if (response.code === 0) {
        console.log('✅ 使用真实API删除通知成功')
        return response.data
      } else {
        throw new Error(response.message || '删除通知失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟删除通知')
        return this.mockDeleteNotification(id)
      }
      console.error('❌ 后端API删除通知失败，使用模拟数据:', error)
      return this.mockDeleteNotification(id)
    }
  },

  // 批量标记已读
  async batchMarkAsRead(ids) {
    try {
      const response = await apiClient.post('/notifications/batch/read', { ids })
      
      if (response.code === 0) {
        console.log('✅ 使用真实API批量标记已读成功')
        return response.data
      } else {
        throw new Error(response.message || '批量标记已读失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟批量标记已读')
        return this.mockBatchMarkAsRead(ids)
      }
      console.error('❌ 后端API批量标记已读失败，使用模拟数据:', error)
      return this.mockBatchMarkAsRead(ids)
    }
  },

  // 批量标记未读
  async batchMarkAsUnread(ids) {
    try {
      const response = await apiClient.post('/notifications/batch/unread', { ids })
      
      if (response.code === 0) {
        console.log('✅ 使用真实API批量标记未读成功')
        return response.data
      } else {
        throw new Error(response.message || '批量标记未读失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟批量标记未读')
        return this.mockBatchMarkAsUnread(ids)
      }
      console.error('❌ 后端API批量标记未读失败，使用模拟数据:', error)
      return this.mockBatchMarkAsUnread(ids)
    }
  },

  // 批量删除
  async batchDelete(ids) {
    try {
      const response = await apiClient.post('/notifications/batch/delete', { ids })
      
      if (response.code === 0) {
        console.log('✅ 使用真实API批量删除成功')
        return response.data
      } else {
        throw new Error(response.message || '批量删除失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟批量删除')
        return this.mockBatchDelete(ids)
      }
      console.error('❌ 后端API批量删除失败，使用模拟数据:', error)
      return this.mockBatchDelete(ids)
    }
  },

  // 获取未读通知数量
  async getUnreadCount() {
    try {
      const response = await apiClient.get('/notifications/unread-count')
      
      if (response.code === 0) {
        console.log('✅ 使用真实API获取未读数量成功')
        return response.data
      } else {
        throw new Error(response.message || '获取未读数量失败')
      }
    } catch (error) {
      if (error.isFallback || error.message === 'BACKEND_UNAVAILABLE') {
        console.log('⚠️ 后端服务不可用，使用模拟未读数量')
        return this.mockGetUnreadCount()
      }
      console.error('❌ 后端API获取未读数量失败，使用模拟数据:', error)
      return this.mockGetUnreadCount()
    }
  },

  // 模拟方法
  mockGetNotifications(params) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟通知数据')
        let result = [...mockNotifications]
        
        // 应用筛选
        if (params.type) {
          result = result.filter(n => n.type === params.type)
        }
        if (params.priority) {
          result = result.filter(n => n.priority === params.priority)
        }
        if (params.status) {
          result = result.filter(n => n.status === params.status)
        }
        if (params.keyword) {
          const keyword = params.keyword.toLowerCase()
          result = result.filter(n => 
            n.title.toLowerCase().includes(keyword) ||
            n.content.toLowerCase().includes(keyword)
          )
        }
        
        resolve({
          notifications: result,
          total: result.length,
          page: params.page || 1,
          size: params.size || 20
        })
      }, 300)
    })
  },

  mockGetNotification(id) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟通知详情数据')
        const notification = mockNotifications.find(n => n.id === id)
        resolve(notification || null)
      }, 200)
    })
  },

  mockSendNotification(notificationData) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟发送通知数据')
        const newNotification = {
          id: mockNotifications.length + 1,
          ...notificationData,
          status: 'unread',
          createdAt: new Date().toISOString(),
          readAt: null
        }
        mockNotifications.unshift(newNotification)
        resolve(newNotification)
      }, 500)
    })
  },

  mockMarkAsRead(id) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟标记已读数据')
        const notification = mockNotifications.find(n => n.id === id)
        if (notification) {
          notification.status = 'read'
          notification.readAt = new Date().toISOString()
        }
        resolve(notification)
      }, 200)
    })
  },

  mockMarkAsUnread(id) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟标记未读数据')
        const notification = mockNotifications.find(n => n.id === id)
        if (notification) {
          notification.status = 'unread'
          notification.readAt = null
        }
        resolve(notification)
      }, 200)
    })
  },

  mockDeleteNotification(id) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟删除通知数据')
        const index = mockNotifications.findIndex(n => n.id === id)
        if (index !== -1) {
          mockNotifications.splice(index, 1)
        }
        resolve({ success: true })
      }, 200)
    })
  },

  mockBatchMarkAsRead(ids) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟批量标记已读数据')
        ids.forEach(id => {
          const notification = mockNotifications.find(n => n.id === id)
          if (notification) {
            notification.status = 'read'
            notification.readAt = new Date().toISOString()
          }
        })
        resolve({ success: true, count: ids.length })
      }, 300)
    })
  },

  mockBatchMarkAsUnread(ids) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟批量标记未读数据')
        ids.forEach(id => {
          const notification = mockNotifications.find(n => n.id === id)
          if (notification) {
            notification.status = 'unread'
            notification.readAt = null
          }
        })
        resolve({ success: true, count: ids.length })
      }, 300)
    })
  },

  mockBatchDelete(ids) {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟批量删除数据')
        ids.forEach(id => {
          const index = mockNotifications.findIndex(n => n.id === id)
          if (index !== -1) {
            mockNotifications.splice(index, 1)
          }
        })
        resolve({ success: true, count: ids.length })
      }, 300)
    })
  },

  mockGetUnreadCount() {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('📋 使用模拟未读数量数据')
        const count = mockNotifications.filter(n => n.status === 'unread').length
        resolve({ count })
      }, 200)
    })
  }
}

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}